/**
 * Created by oneminute on 8/26/14.
 */

var amqp = require("amqp");
//var common = require("common");
var lz = require("../../lib/utils/modules")();

var options = {
    host: "192.168.0.150",
    port: 5672,
    login: 'oneminute',
    password: '690854LR',
    connectionTimeout: 0,
    authMechanism: "AMQPLAIN",
    vhost: '/',
    ssl: {
        enabled: false
    },
    clientproperties: {
        applicationname: "iwant_server"
    }
};

var implOptions = {
    defaultExchangeName: "amq.topic"
};

var connection = amqp.createConnection(options, implOptions, function () {
    lz.Logger.info("connection ready");
});

connection.on("error", function (_err) {
    lz.Logger.error("Error: ", _err);
});

connection.on("close", function (_err) {
    lz.Logger.info("Connection closed.");
});

connection.on("ready", function (_err) {
    lz.Logger.info("ready");
    connection.exchange('iwant-exchange', {type: "topic"}, function (_exchange) {
        lz.Logger.info("Exchange " + _exchange.name + " is open.");

        var count = 10;
        var timer = setInterval(function () {
            var routingKey = "m0" + ((count % 2) + 1);
            lz.Logger.info("send message to [%s]. ", routingKey, count);
            _exchange.publish(routingKey, {body: "hello world " + count}, {}, function () {
                lz.Logger.info("sent");
            });
            if (--count == 0) {
                clearTimeout(timer);
            }
        }, 800);

        connection.queue('iwant-queue1', {}, function (_queue) {
            lz.Logger.info("Queue: %s is open.", _queue.name);
            setTimeout(function () {

            }, 10000);
            _queue.bind(_exchange.name, "m01");
            _queue.on("queueBindOk", function () {
                lz.Logger.info("[%s]queue bind ok.", _queue.name);
                lz.Logger.info("[%s]注册订阅者.", _queue.name);
                _queue.subscribe({}, function (_msg) {
                    lz.Logger.info("[%s] %j", _queue.name, _msg);
                    //_queue.shift(true);
                });
            });
        });

        connection.queue('iwant-queue2', {}, function (_queue) {
            lz.Logger.info("Queue: %s is open.", _queue.name);
            setTimeout(function () {

            }, 10000);
            _queue.bind(_exchange.name, "m02");
            _queue.on("queueBindOk", function () {
                lz.Logger.info("[%s]queue bind ok.", _queue.name);
                lz.Logger.info("[%s]注册订阅者.", _queue.name);
                _queue.subscribe({}, function (_msg) {
                    lz.Logger.info("[%s] %j", _queue.name, _msg);
                    //_queue.shift(true, true);
                })
            });
        });
    });

});

process.on("exit", function () {
    connection.disconnect();
    lz.Logger.info("exit");
});
